package com.tianhui.consignortwofei.mvp.ui.fragment.audit;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.fgs.common.imageView.PictureDialog;
import com.fgs.common.other.CommonEvent;
import com.fgs.common.utils.CheckUtil;
import com.tianhui.consignortwofei.R;
import com.tianhui.consignortwofei.base.BaseDataListFragment;
import com.tianhui.consignortwofei.constant.KeyValue;
import com.tianhui.consignortwofei.interf.OnSearchClearListener;
import com.tianhui.consignortwofei.interf.OnSearchClickListener;
import com.tianhui.consignortwofei.mvp.contract.VehicleContract;
import com.tianhui.consignortwofei.mvp.model.enty.VehicleInfo;
import com.tianhui.consignortwofei.mvp.presenter.VehiclePresenter;
import com.tianhui.consignortwofei.mvp.ui.activity.audit.SearchActivity;
import com.tianhui.consignortwofei.mvp.ui.activity.audit.vehicle.BindDriverActivity;
import com.tianhui.consignortwofei.mvp.ui.activity.audit.vehicle.VehicleFrontAuditActivity;
import com.tianhui.consignortwofei.mvp.ui.activity.audit.vehicle.VehicleRemarkActivity;
import com.tianhui.consignortwofei.mvp.ui.adapter.VehicleListAdapter;
import com.tianhui.consignortwofei.other.EventWhat;
import com.xuexiang.xui.widget.dialog.materialdialog.DialogAction;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;

import org.yczbj.ycrefreshviewlib.adapter.RecyclerArrayAdapter;
import org.yczbj.ycrefreshviewlib.inter.OnItemChildClickListener;

import java.util.HashMap;
import java.util.Map;

/**
 * @author fgs
 * @date 2020/12/25
 * @description
 **/
public class VehicleListFragment extends BaseDataListFragment<VehicleContract.View, VehicleContract.Presenter> implements VehicleContract.View, OnSearchClickListener {

    private String mAuditStatus = "-1";
    private String mSearchKey;
    private boolean isNeedRefresh;
    private boolean isFirstVisible = true;
    private OnSearchClearListener onSearchClearListener;

    public VehicleListFragment() {
        // Required empty public constructor
    }

    public VehicleListFragment setOnSearchClearListener(OnSearchClearListener onSearchClearListener) {
        this.onSearchClearListener = onSearchClearListener;
        return this;
    }

    public static VehicleListFragment newInstance(String auditStatus) {
        VehicleListFragment driverListFragment = new VehicleListFragment();
        Bundle bundle = new Bundle();
        bundle.putString(KeyValue.KEY_STATUS, auditStatus);
        driverListFragment.setArguments(bundle);
        return driverListFragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_driver_list;
    }

    @Override
    protected VehicleContract.View createView() {
        return this;
    }

    @Override
    protected VehicleContract.Presenter createPresenter() {
        return new VehiclePresenter(getContext());
    }


    @Override
    public RecyclerArrayAdapter createAdapter() {
        return new VehicleListAdapter(getContext());
    }

    @Override
    protected void initListener() {
//        mAdapter.setOnItemClickListener(new OnItemClickListener() {
//            @Override
//            public void onItemClick(int position) {
//                VehicleInfo info = (VehicleInfo) mAdapter.getAllData().get(position);
//                if (info != null) {
//                    Bundle bundle = new Bundle();
//                    bundle.putString(KeyValue.KEY_PLATE_NUMBER, info.vehiclenum);
//                    openActivity(VehicleFrontAuditActivity.class, bundle);
//                }
//            }
//        });
        mAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(View view, int position) {
                VehicleInfo info;
                switch (view.getId()) {
                    case R.id.item_vehicle_list_submitTextView:
                        showCreateStatementDialog(position);
                        break;
                    case R.id.item_vehicle_list_signatureTextView:
                        checkSignature(position);
                        break;
                    case R.id.item_vehicle_list_operateButton:
                        info = (VehicleInfo) mAdapter.getAllData().get(position);
                        if (info != null) {
                            Bundle bundle = new Bundle();
                            bundle.putParcelable(KeyValue.KEY_VEHICLE_INFO, info);
                            openActivity(BindDriverActivity.class, bundle);
                        }
                        break;
                    case R.id.item_vehicle_list_editButton:
                        info = (VehicleInfo) mAdapter.getAllData().get(position);
                        if (info != null) {
                            Bundle bundle = new Bundle();
                            bundle.putString(KeyValue.KEY_PLATE_NUMBER, info.vehiclenum);
                            bundle.putInt(KeyValue.KEY_OPERATE, KeyValue.KEY_EDIT_OPERATE);
                            openActivity(VehicleFrontAuditActivity.class, bundle);
                        }
                        break;
                    case R.id.item_vehicle_list_auditButton:
                        info = (VehicleInfo) mAdapter.getAllData().get(position);
                        if (info != null) {
                            Bundle bundle = new Bundle();
                            bundle.putString(KeyValue.KEY_PLATE_NUMBER, info.vehiclenum);
                            bundle.putInt(KeyValue.KEY_OPERATE, KeyValue.KEY_AUDIT_OPERATE);
                            openActivity(VehicleFrontAuditActivity.class, bundle);
                        }
                        break;
                    case R.id.item_vehicle_list_remarkButton:
                        info = (VehicleInfo) mAdapter.getAllData().get(position);
                        if (info != null) {
                            Bundle bundle = new Bundle();
                            bundle.putString(KeyValue.KEY_PLATE_NUMBER, info.vehiclenum);
                            bundle.putInt(KeyValue.KEY_OPERATE, KeyValue.KEY_EDIT_OPERATE);
                            openActivity(VehicleRemarkActivity.class, bundle);
                        }
                    case R.id.item_vehicle_list_statusButton:
                        info = (VehicleInfo) mAdapter.getAllData().get(position);
                        if (info != null) {
                            showTingYunDialog(info);
                        }
                        break;
                }
            }
        });

    }

    private void changeVehicleStatus(VehicleInfo info) {
        Map<String, String> map = new HashMap<>();
        map.put("id", info.id);
        map.put("istatus", getVehicleStatus(info.istatus));
        getPresenter().requestChangeVehicleStatus(map, true);
    }

    private String getVehicleStatus(String status) {
        if (!TextUtils.isEmpty(status) && status.equals("0")) {
            status = "1";
        } else {
            status = "0";
        }
        return status;
    }

    private void checkSignature(int position) {
        Object object = mAdapter.getAllData().get(position);
        VehicleInfo vehicleInfo;
        if (object instanceof VehicleInfo) {
            vehicleInfo = (VehicleInfo) object;
            if (!TextUtils.isEmpty(vehicleInfo.imgsignimage)) {
                showSignatureDialog(vehicleInfo.imgsignimage);
            } else {
                showToast("未找到签名信息");
            }
        }
    }

    private void showSignatureDialog(String imageId) {
        new PictureDialog(getContext()).setImageId(imageId).show();
    }

    private void showCreateStatementDialog(int position) {
        VehicleInfo vehicleInfo = (VehicleInfo) mAdapter.getAllData().get(position);
        if (vehicleInfo != null) {
            new MaterialDialog.Builder(getContext())
                    .content("确认要为此车辆重新生成挂靠声明？")
                    .positiveText("是")
                    .negativeText("否")
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            requestCreateStatement(vehicleInfo);
                        }
                    })
                    .show();
        }

    }


    private void showTingYunDialog(VehicleInfo info) {
//        VehicleInfo vehicleInfo = (VehicleInfo) mAdapter.getAllData().get(position);
//        istatus;//是否启用 0 未启用 1 已启用
        String tingYunText="";
        if (!TextUtils.isEmpty(info.istatus)&&info.istatus.equals("0")){
            tingYunText="确定要启用车辆？";
        }else {
            tingYunText="确定要停运车辆？";
        }
        if (info != null) {
            new MaterialDialog.Builder(getContext())
                    .content(tingYunText)
                    .positiveText("是")
                    .negativeText("否")
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
//                            requestCreateStatement(vehicleInfo);
                            changeVehicleStatus(info);
                        }
                    })
                    .show();
        }

    }




    private void requestCreateStatement(VehicleInfo vehicleInfo) {
        if (!TextUtils.isEmpty(vehicleInfo.drivertel) &&
                !TextUtils.isEmpty(vehicleInfo.signimage) &&
                !TextUtils.isEmpty(vehicleInfo.defaultvehicle)
                && vehicleInfo.defaultvehicle.equals("1")) {
            Map<String, String> map = new HashMap<>();
            map.put("driverTel", vehicleInfo.drivertel);
            getPresenter().requestCreateStatement(map, true);
        } else {
            showToast("请检查是否有司机将其设为默认车辆并且签名照齐全，暂时不能重新生成挂靠声明");
        }

    }

    @Override
    public void requestDataList(int page, boolean isDialog) {
        Map<String, String> map = new HashMap<>();
        map.put("limit", "10");
        map.put("order", "desc");
        map.put("page", page + "");
        map.put("sort", "create_time");
        if (!TextUtils.isEmpty(mAuditStatus)) {
            map.put("isaudit", mAuditStatus);
        }
        if (!TextUtils.isEmpty(mSearchKey)) {
            if (CheckUtil.isChineseCharacters(mSearchKey) || CheckUtil.isMobileNO(mSearchKey)) {
                map.put("drivername", mSearchKey);
            } else {
                map.put("vehiclenum", mSearchKey);
            }
        }
        getPresenter().requestVehicleList(map, isDialog);
    }

    @Override
    public void initData() {
        Bundle bundle = getArguments();

        if (bundle != null && !bundle.isEmpty()) {
            mAuditStatus = bundle.getString(KeyValue.KEY_STATUS);
        }

    }

    @Override
    public void onSearch(String searchKey) {
        this.mSearchKey = searchKey;
        refreshData(true);
    }

    @Override
    protected void onUserVisible() {
        super.onUserVisible();
        if (getActivity() instanceof SearchActivity) {
            ((SearchActivity) getActivity()).setOnSearchClickListener(this);
        }

        if (isNeedRefresh && !isFirstVisible) {
            refreshData(true);
            isNeedRefresh = false;
        }
        if (isFirstVisible) {
            isFirstVisible = false;
            isNeedRefresh = false;
        }
        Toast.makeText(getContext(), "数据已刷新", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void refreshOperate() {
        super.refreshOperate();
        mSearchKey = "";
        if (null != onSearchClearListener) {
            onSearchClearListener.onSearchClear();
        }
    }

    @Override
    public void onEvent(CommonEvent event) {
        super.onEvent(event);
        switch (EventWhat.valueOf(event.getWhat())) {
            case EVENT_REFRESH_VEHICLE_LIST:
                isNeedRefresh = true;
                break;
        }
    }


    @Override
    public void refreshVehicleStatus() {
        refreshData(true);
    }
}
